package org.xqp.hrm.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.xqp.hrm.handler.MyAuthenticationFailureHandler;
import org.xqp.hrm.handler.MyAuthenticationSuccessHandler;
import org.xqp.hrm.mapper.PermissionMapper;


@Configuration // 这是spring配置类
@EnableWebSecurity // 开启Security
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启全局方法注解配置权限
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    //配置认证管理器，授权模式为“password”时会用到
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    //使用哪个密码编码器：有加密的不加密的和一些其他的  我们这里用的的加密的
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    
    //授权规则配置   对url的权限配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests()                                //授权配置
                .antMatchers("/login").permitAll()  //登录路径放行
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
                //.loginPage("/login.html")   //指定登录页面
                //.loginProcessingUrl("/login")   //登录提交地址
                //.successForwardUrl("/loginSuccess")             // 设置登陆成功页
                .successHandler(new MyAuthenticationSuccessHandler())//认证成功结果处理器 返回给前端数据
                .failureHandler(new MyAuthenticationFailureHandler())   //认证失败处理器  返回给前端数据
                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨域伪造检查
    }
}